#include <iostream>
#include <iomanip>
using namespace std;

const int N = 100010;

struct Node
{
    int val, next;
} nodes[N];

bool vis[N];
int p[2];
int link[2][N];

int main()
{
    int start, n;
    cin >> start >> n;
    while (n--)
    {
        int id;
        cin >> id >> nodes[id].val >> nodes[id].next;
    }
    int s = start;
    while (s != -1)
    {
        if (!vis[abs(nodes[s].val)])
        {
            vis[abs(nodes[s].val)] = true;
            link[0][p[0]] = s;
            link[0][++p[0]] = -1;
        }
        else
        {
            link[1][p[1]] = s;
            link[1][++p[1]] = -1;
        }
        s = nodes[s].next;
    }
    for (int j = 0; j < 2; j++)
    {
        for (int i = 0; i < p[j]; i++)
        {
            if (link[j][i + 1] != -1)
            {
                cout << setw(5) << setfill('0') << link[j][i] << " " << nodes[link[j][i]].val << " " << setw(5) << setfill('0') << link[j][i + 1] << endl;
            }
            else
            {
                cout << setw(5) << setfill('0') << link[j][i] << " " << nodes[link[j][i]].val << " " << -1 << endl;
            }
        }
    }
    return 0;
}